/**
 * @Author: lll
 * @Email:li.lele@vpclub.cn
 * @Date: create in 2020/6/28
 */
package cn.vpclub.admin.web.home;

import cn.vpclub.admin.util.GetIpUtil;
import com.google.code.kaptcha.Producer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(value = "login")
public class LoginController {
    Logger log = LoggerFactory.getLogger(LoginController.class);
    private Producer producer;

    @Autowired
    public void setCaptchaProducer(Producer producer) {
        this.producer = producer;
    }

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @RequestMapping(value = "getVertifyCode/{time}")
    public void getVertifyCode(@PathVariable Long time, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        httpServletResponse.addHeader("Cache-Control", "post-check=0, pre-check=0");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setContentType("image/jpeg");
        String capText = producer.createText();
        String ip = GetIpUtil.getIpAddress(httpServletRequest);
        log.info("获取当前请求的时间戳{}", time);
        log.info("获取验证码文本值{}", capText);
        log.info("获取当前请求的ip地址{}", ip);
        stringRedisTemplate.opsForValue().set(time.toString() + ip, capText, 60 * 5, TimeUnit.SECONDS);
        BufferedImage bufferedImage = producer.createImage(capText);
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        ImageIO.write(bufferedImage, "jpg", servletOutputStream);
        try {
            servletOutputStream.flush();
        } finally {
            servletOutputStream.close();
        }
    }
}
